package com.nineclock.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.config.HxImManager;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SmsService smsService;

    @Autowired
    SysUserMapper userMapper;

    @Override
    public SysUserDTO queryUser(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //无论是 用户名还是手机号都可以登录
        wrapper.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile ,username);
        wrapper.eq(SysUser::getStatus, 1);


        SysUser user = userMapper.selectOne(wrapper);
        if(user != null){
            return BeanHelper.copyProperties(user, SysUserDTO.class);
        }

        return null;
    }


    @Autowired
    HxImManager hxImManager;
    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        //健壮性判断
        if(sysRegisterDTO == null || sysRegisterDTO.getMobile() == null || sysRegisterDTO.getPassword() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //校验验证码
        Boolean flag
                = smsService.verify(sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if(!flag){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        //封装user对象
        SysUser user = new SysUser();
        user.setMobile(sysRegisterDTO.getMobile());
        user.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        user.setStatus((short)1);
        user.setCreateTime(new Date());
        //存储到数据库中
        userMapper.insert(user);

        //注册到环信云
        SysUser u = new SysUser();
        u.setUsername(sysRegisterDTO.getMobile());
        u.setPassword("123456");
        hxImManager.registerUser2HuanXing(u);

        //返回 用户id
        return user.getId();
    }
}
